<template>
  <div>
    <el-row>
      <el-cascader size="large" :props="{ expandTrigger: 'hover' }" :options="options" v-model="selectedOptions" @change="handleChange">
      </el-cascader>
      <el-input clearable v-model.trim="Shop_name" placeholder="请输入名称查询" prefix-icon="el-icon-search" style="width:400px"></el-input>
      <el-button type="primary" plain @click="searchShop" icon="el-icon-search">搜索</el-button>
      <el-button type="info" plain icon="el-icon-shopping-cart-2" @click="showAddShop" style="margin-left: 40px;">添加商铺</el-button>
    </el-row>
    <el-table :data="tableData" height="730" v-loading="tableLoading" element-loading-text="加载中" element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(5,22,48)" style="width: 100%;margin-top: 10px;font-size: 16px;" :cell-style="columnStyle">
      <el-table-column prop="name" label="名称" width="330">
        <template slot-scope="scope">
          <i class="el-icon-shopping-cart-1"></i>
          <span style="margin-left: 10px">{{ scope.row.name }}</span>

        </template>
      </el-table-column>
      <el-table-column prop="province" width="110" label="省/直辖市">
      </el-table-column>
      <el-table-column prop="city" width="110" label="市/区">
      </el-table-column>
      <el-table-column prop="region" width="130" label="区/县">
      </el-table-column>
      <el-table-column prop="address" width="300" label="地址">
      </el-table-column>

      <el-table-column width="280" prop="type" label="类型/标签">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top" width="250" :open-delay=600>

            <el-tag v-for="(item,index) in scope.row.type.split(';')" :key="index" type="success" style="margin:10px">{{ item }}</el-tag>

            <div slot="reference" class="name-wrapper">
              <el-tag style="font-size: 15px;" type="info">{{ scope.row.type.split(";")[0] }}</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button slot="reference" size="medium" type="info" plain icon="el-icon-info" @click="handleInfo(scope.$index, scope.row)"></el-button>
          <el-button size="medium" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)"></el-button>

          <el-button slot="reference" size="medium" type="danger" plain icon="el-icon-delete" @click="handleDelete(scope.$index, scope.row)">
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="block" style="margin-top:20px">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page_num" :page-sizes="[4, 8, 12, 16]"
        :page-size="page_size" layout="total, sizes, prev, pager, next, jumper" :total="total_size">
      </el-pagination>
    </div>

    <el-drawer title="购物场所编辑" @open="drawerOpen" :with-header="false" :visible.sync="editVisible" direction="rtl" custom-class="demo-drawer"
      ref="drawer" size="65%" :modal-append-to-body="false">
      <el-card class="box-card" shadow="always" style="margin:100px 40px 0 40px;">

        <div slot="header" class="clearfix">
          <span>购物场所信息更新</span>
        </div>
        <el-form :model="formData" label-width="120px" ref="form" :rules="rules">
          <el-form-item label="名称" prop="name">
            <el-input v-model="formData.name" style="width:30%" placeholder="请输入名称"></el-input>
          </el-form-item>
          <!-- <el-row>
            <el-col :span="10"> -->
          <el-form-item label="地址">
            <el-cascader size="medium" :props="{ expandTrigger: 'hover' }" :options="editOptions" v-model="editSelect">
            </el-cascader>
          </el-form-item>

          <!-- </el-col>
            <el-col :span="10"> -->

          <el-form-item label="详细地址" label-width="120px" prop="address">
            <el-input v-model="formData.address" placeholder="请输入完整地址"></el-input>
          </el-form-item>

          <!-- </el-col>
          </el-row> -->
          <el-row>
            <el-col :span="8">
              <el-form-item label="经度" prop="longitude">
                <el-input v-model="formData.longitude"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" style="margin-left:54px">
              <el-form-item label="纬度" prop="latitude">
                <el-input v-model="formData.latitude"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="类型">
            <el-input v-model="formData.type" placeholder="不同标签使用分号间隔" style="width:50%"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="editVisible = false">取消</el-button>
            <el-button type="primary" plain @click="SubmitSite">更新信息</el-button>
          </el-form-item>
        </el-form>
      </el-card>

    </el-drawer>

    <el-dialog :visible.sync="addShopDialogVisible" :modal-append-to-body=false width="60%" title="新增购物" style="background-color:#334d4f07 ">
      <el-form :model="formData" label-width="190px" ref="addForm" :rules="rules">

        <el-form-item label="店铺名称" prop="name">
          <el-input v-model="formData.name" style="width:30%" placeholder="请输入名称"></el-input>
        </el-form-item>
        <!-- <el-row>
          <el-col :span="10"> -->

        <el-form-item label="地址">
          <el-cascader placeholder="请选择" size="medium" :props="{ expandTrigger: 'hover' }" :options="addOptions" v-model="addSelect">
          </el-cascader>
        </el-form-item>

        <!-- </el-col>
          <el-col :span="10"> -->

        <el-form-item label="详细地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入完整地址" style="width:50%"></el-input>
        </el-form-item>

        <!-- </el-col>
        </el-row> -->

        <el-row>
          <el-col :span="8">
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="formData.longitude"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left:54px">
            <el-form-item label="纬度" prop="latitude">
              <el-input v-model="formData.latitude"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="类型">
          <el-input v-model="formData.type" style="width:50%"></el-input>
        </el-form-item>
        <el-form-item style="margin-top:80px">
          <el-button @click="addShopDialogVisible = false">取消</el-button>
          <el-button type="primary" plain @click="addShop">添加</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="地点信息" :visible.sync="mapVisible" width="50%" :modal-append-to-body="false" :append-to-body="false">
      <div id="mapCon" style="width: 100%; height: 500px;"></div>
    </el-dialog>

  </div>
</template>

<script>
import { v4 as uuidv4 } from 'uuid';
import { transformData } from '@/common/map_utils/json_util.js'
import { regionDataPlus,CodeToText,regionData,TextToCode } from 'element-china-area-data'

var map=null;
export default {
  data() {
    return {
      mapVisible: false,
      keyValue: "200263f8a71b9f84b59f829867957431",
      tableData: [],
      tableLoading: true,
      total_size: 0,
      page_num: 1,
      page_size: 12,
      Shop_name: '',
      options: regionDataPlus,
      selectedOptions: ["110000",""],
      formData: {
        id: '',
        name: '',
        province: '',
        city: '',
        region: '',
        address: '',
        longitude: '',
        latitude: '',
        type: '',
      },
      editVisible: false,
      editOptions: regionData,
      editSelect: [],
      addShopDialogVisible: false,
      addOptions: regionData,
      addSelect: [],
      rules: {
        name: [
          { required: true,message: '名称不能为空',trigger: 'blur' },
          { min: 2,max: 20,message: '名称长度在 2 到 20 个字符',trigger: 'blur' }],
        address: [
          { required: true,message: '详细地址不能为空',trigger: 'blur' },
          { min: 4,max: 50,message: '详细地址长度在 4 到 50 个字符',trigger: 'blur' }],
        longitude: [
          { required: true,message: '经度不能为空',trigger: 'blur' },
          { validator: this.validateLongitude,message: '经度必须为数字',trigger: 'blur' }],
        latitude: [
          { required: true,message: '纬度不能为空',trigger: 'blur' },
          { validator: this.validateLatitude,message: '纬度必须为数字',trigger: 'blur' }],
      },
    };
  },

  computed: {
    provinceS() {

      if(this.selectedOptions[0]) {
        var str=CodeToText[this.selectedOptions[0]];
        return str;
      } else {
        return '';
      }

    },
    cityS() {

      if(this.selectedOptions[1]&&this.selectedOptions[1]!='') {
        var str=CodeToText[this.selectedOptions[1]];
        return str==='市辖区'? this.provinceS:str;
      } else {
        return '';
      }
    },
    regionS() {

      if(this.selectedOptions[2]&&this.selectedOptions[2]!='') {
        var str=CodeToText[this.selectedOptions[2]];
        return str;
      } else {
        return '';
      }
    }
  },
  methods: {
    columnStyle({ row,column,rowIndex,columnIndex }) {
      if(columnIndex==0) {
        return "color:#B3D8FF"
      }
      if(columnIndex==4) {
        return "color:#E1F3D8"
      }

    },
    validateLongitude(rule,value,callback) {
      if(value==='') {
        callback(new Error('经度不能为空'));
      } else if(!/^-?\d+(\.\d+)?$/.test(value)) {
        callback(new Error('经度必须为数字'));
      } else {
        callback();
      }
    },
    validateLatitude(rule,value,callback) {
      if(value==='') {
        callback(new Error('纬度不能为空'));
      } else if(!/^-?\d+(\.\d+)?$/.test(value)) {
        callback(new Error('纬度必须为数字'));
      } else {
        callback();
      }
    },
    //获取数据
    loadMapData(Shop_name=this.Shop_name,province=this.provinceS,city=this.cityS,region=this.regionS) {
      this.tableLoading=true;
      var queryStruct=new Zondy.Service.QueryFeatureStruct()
      //是否包含几何图形信息
      queryStruct.IncludeGeometry=true
      //是否包含属性信息
      queryStruct.IncludeAttribute=true
      //是否包含图形显示参数
      queryStruct.IncludeWebGraphic=false

      var queryParam=new Zondy.Service.QueryByLayerParameter("gdbp://MapGisLocal/itravel/sfcls/全国购物",{
        resultFormat: 'json',
        struct: queryStruct,
      });
      //设置查询分页号
      queryParam.pageIndex=this.page_num-1;
      //设置查询要素数目
      queryParam.recordNumber=this.page_size

      var region_option="name like '%"+Shop_name+"%' and province like '%"+province+"%'";
      region_option=region_option.concat("and city like '%").concat(city).concat("%' and region like '%").concat(region).concat("%'")

      //属性查询
      queryParam.where=region_option

      var queryService=new Zondy.Service.QueryLayerFeature(queryParam,{
        ip: window.server.GIS_IP,
        port: window.server.GIS_PORT, //访问IGServer的端口号，.net版为6163，Java版为8089
      })
      //执行查询操作，querySuccess为查询回调函数
      queryService.query(this.querySuccess,this.queryError)

    },
    //查询成功
    querySuccess(result) {
      this.tableLoading=false;
      this.total_size=result.TotalCount;
      var data=transformData(result);
      this.tableData=data;

    },

    queryError(e) {
      console.log(e);
    },
    //搜索
    searchShop() {
      this.loadMapData()
    },
    handleChange(value) {
      // this.loadMapData();
    },
    //改变页条数
    handleSizeChange(val) {
      this.page_size=val;
      this.loadMapData();
    },
    //翻页
    handleCurrentChange(val) {
      this.page_num=val;
      this.loadMapData();
    },
    //添加弹窗
    showAddShop() {
      //信息置空
      this.formData=this.$options.data().formData;
      this.addSelect=[]
      this.addShopDialogVisible=true
    },

    addPoint(longi,lati,attValue) {
      let lonlat=[longi,lati];
      let mercator=ol.proj.transform(lonlat,'EPSG:4326','EPSG:3857')
      // let pointInMercator = new ol.geom.Point(mercator);
      var gpoint=new Zondy.Object.GPoint(mercator[0],mercator[1])

      const point=new Zondy.Object.FeatureGeometry({
        PntGeom: [gpoint]
      });

      //描述点要素的符号参数信息
      var pointInfo=new Zondy.Object.CPointInfo({
        //子图角度，取值范围为0~360。
        Angle: 0,
        //子图颜色（请参考MapGIS颜色库中颜色编号）
        Color: 6,
        //子图高度
        SymHeight: 10,
        //子图ID（请参考MapGIS符号库中线符号编号）
        SymID: 1,
        //子图宽度
        SymWidth: 10
      });

      //设置当前点要素的图形参数信息
      var webGraphicInfo=new Zondy.Object.WebGraphicsInfo({
        InfoType: 1,
        PntInfo: pointInfo
      });

      //创建一个要素
      var feature=new Zondy.Object.Feature({
        fGeom: point,
        GraphicInfo: webGraphicInfo,
        AttValue: attValue   //设置添加点要素的属性信息
      });
      //设置要素为点要素
      feature.setFType(1);
      //创建一个要素数据集
      var featureSet=new Zondy.Object.FeatureSet();
      featureSet.clear();
      //设置属性结构，根据图层属性进行设置
      var cAttStruct=new Zondy.Object.CAttStruct({
        FldName: ["id","name","address","province","city",
          "region","longitude","latitude","type"],
        FldNumber: 9,
        FldType: ["string","string","string","string","string",
          "string","double","double","string"]
      });
      featureSet.AttStruct=cAttStruct;
      //添加要素到要素数据集
      featureSet.addFeature(feature);
      //创建一个编辑服务类
      var editService=new Zondy.Service.EditLayerFeature('gdbp://MapGisLocal/itravel/sfcls/全国购物',{
        ip: window.server.GIS_IP,
        port: window.server.GIS_PORT //访问IGServer的端口号，.net版为6163，Java版为8089
      });
      //执行添加点要素功能
      editService.add(featureSet,this.onAddPntSuccess);

    },
    //点添加回调
    onAddPntSuccess(data) {
      if(data) {
        //刷新图层
        this.$message.success("添加购物场所成功")
        this.addShopDialogVisible=false;
      } else {
        this.$message.error("添加购物场所失败")
      }
    },

    //确定添加场所
    addShop() {
      this.$refs.addForm.validate(valid => {
        if(valid) {
          if(this.addSelect.length<3) {
            this.$message.info("请选择地址");
          } else {
            //添加购物请求
            var id=uuidv4();
            var province;
            var city;
            var region;
            if(this.addSelect[0]) {
              province=CodeToText[this.addSelect[0]];
              city=CodeToText[this.addSelect[1]];
              region=CodeToText[this.addSelect[2]];
              if(city==='市辖区') {
                city=province;
              }
            }

            var attValue=[id,this.formData.name,this.formData.address,province,city,
              region,Number(this.formData.longitude),Number(this.formData.latitude),this.formData.type]


            this.addPoint(Number(this.formData.longitude),Number(this.formData.latitude),attValue)

          }

        } else {
          // 表单验证失败
          return false;
        }
      });
    },
    //打开编辑页面
    drawerOpen() {
    },
    //点击编辑住宿按钮
    handleEdit(index,row) {
      this.editVisible=true;
      this.formData.id=row.id;
      this.formData.name=row.name;
      this.editSelect[0]=TextToCode[row.province].code;
      if(row.province===row.city) {
        this.editSelect[1]=TextToCode[row.province]['市辖区'].code;
        this.editSelect[2]=TextToCode[row.province]['市辖区'][row.region].code;
      } else {
        this.editSelect[1]=TextToCode[row.province][row.city].code;
        this.editSelect[2]=TextToCode[row.province][row.city][row.region].code;
      }

      this.formData.address=row.address;
      this.formData.longitude=row.longitude;
      this.formData.latitude=row.latitude;
      this.formData.type=row.type;
    },
    SubmitSite() {
      this.$refs.form.validate(valid => {
        if(valid) {
          this.editMap();
        } else {
          // 表单验证失败
          return false;
        }
      });
    },

    //购物修改查询
    editMap() {
      var queryStruct=new Zondy.Service.QueryFeatureStruct()
      //是否包含几何图形信息
      queryStruct.IncludeGeometry=true
      //是否包含属性信息
      queryStruct.IncludeAttribute=true
      //是否包含图形显示参数
      queryStruct.IncludeWebGraphic=false

      var queryParam=new Zondy.Service.QueryByLayerParameter('gdbp://MapGisLocal/itravel/sfcls/全国购物',{
        resultFormat: 'json',
        struct: queryStruct,
      });
      //设置查询分页号
      queryParam.pageIndex=0;
      //设置查询要素数目
      queryParam.recordNumber=1
      queryParam.where="id = '".concat(this.formData.id).concat("'");

      var queryService=new Zondy.Service.QueryLayerFeature(queryParam,{
        ip: '127.0.0.1',
        port: window.server.GIS_PORT, //访问IGServer的端口号，.net版为6163，Java版为8089
      });
      //执行查询操作，querySuccess为查询回调函数
      queryService.query(this.queryUpdate,this.queryError);

    },
    // 更新回调
    onPntUpdateSuccess(data) {
      if(data.succeed) {
        this.$message.success("修改信息成功");
        this.editVisible=false;
        this.loadMapData()
      } else {
        this.$message.error("修改失败");
      }
    },
    //更新购物场所
    queryUpdate(result) {
      if(result.TotalCount===0) {
        return;
      }
      var province;
      var city;
      var region;
      if(this.editSelect[0]) {
        province=CodeToText[this.editSelect[0]];
        city=CodeToText[this.editSelect[1]];
        region=CodeToText[this.editSelect[2]];

        if(city==='市辖区') {
          city=province;
        }
      }

      var resultPoint=result;
      resultPoint.SFEleArray[0].AttValue[1]=this.formData.name;
      if(this.editSelect[0]) {
        this.formData.province=CodeToText[this.editSelect[0]];
        this.formData.city=CodeToText[this.editSelect[1]];
        this.formData.region=CodeToText[this.editSelect[2]];
        if(this.formData.city==='市辖区') {
          this.formData.city=this.formData.province;
        }
      }
      if(this.formData.province!='') {
        resultPoint.SFEleArray[0].AttValue[2]=this.formData.province;
        resultPoint.SFEleArray[0].AttValue[3]=this.formData.city;
        resultPoint.SFEleArray[0].AttValue[4]=this.formData.region;
      }
      resultPoint.SFEleArray[0].AttValue[5]=this.formData.longitude;
      resultPoint.SFEleArray[0].AttValue[6]=this.formData.latitude;
      resultPoint.SFEleArray[0].AttValue[7]=this.formData.type;
      resultPoint.SFEleArray[0].AttValue[8]=this.formData.address;
      var editService=new Zondy.Service.EditLayerFeature('gdbp://MapGisLocal/itravel/sfcls/全国购物',{
        ip: '127.0.0.1',
        port: window.server.GIS_PORT //访问IGServer的端口号，.net版为6163，Java版为8089
      });
      editService.update(resultPoint,this.onPntUpdateSuccess);
    },
    //删除住宿场所
    handleDelete(index,row) {

      this.$confirm('确定删除该购物场所?','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var deleteService=new Zondy.Service.EditLayerFeature(
          'gdbp://MapGisLocal/itravel/sfcls/全国购物',
          {
            ip: window.server.GIS_IP,
            port: window.server.GIS_PORT //访问IGServer的端口号，.net版为6163，Java版为8089
          }
        );
        deleteService.deletes(row.FID,this.onDeleteSuccess);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    onDeleteSuccess(rlt) {
      if(rlt) {
        this.$message.success("删除购物场所成功")
        this.loadMapData()
      } else {
        this.$message.error("删除购物场所失败")
      }
    },
    initMap() {
      if(!map) {
        // map=null;

        //初始化地图容器
        map=new ol.Map({
          //目标DIV
          target: 'mapCon',
          view: new ol.View({
            projection: ol.proj.get("EPSG:3857"),
            center: ol.proj.fromLonLat([this.lon_x,this.lan_y]),
            minZoom: 10,
            zoom: 17,
          }),
          //将图层添加到地图容器
          layers: [
            new ol.layer.Tile({
              name: "天地图矢量图层",
              source: new ol.source.XYZ({
                url: "http://t0.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk="+this.keyValue, //为天地图密钥,
                wrapX: false
              })
            }),
            new ol.layer.Tile({
              name: "天地图矢量注记图层",
              source: new ol.source.XYZ({
                url: "http://t0.tianditu.com"+"/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk="+this.keyValue,
                wrapX: false
              })
            })
          ],

        });
      }

    },
    removeMarker() {
      // 移除最后一个图层
      var layers=map.getLayers();
      if(layers.getLength()>2) {
        var lastLayer=layers.item(layers.getLength()-1);
        map.removeLayer(lastLayer);
      }
    },

    addMarker(name_site) {
      var iconFeature=new ol.Feature({
        geometry: new ol.geom.Point(ol.proj.fromLonLat([this.lon_x,this.lan_y])),
        name: name_site,
        population: 4000,
        rainfall: 500
      });

      var iconStyle=new ol.style.Style({
        image: new ol.style.Icon(      /** @type {olx.style.IconOptions} */
          ({
            anchor: [0.5,46],
            anchorXUnits: 'fraction',
            anchorYUnits: 'pixels',
            scale: 1,
            src: require('../../../assets/marker/supermarket.png')
          })),
        text: new ol.style.Text({
          //位置
          offsetY: 4,
          textAlign: 'center',
          //基准线
          textBaseline: 'middle',
          //文字样式
          font: 'bold 15px 微软雅黑',
          text: name_site,
          fill: new ol.style.Fill({ color: '#223458' }),
          stroke: new ol.style.Stroke({ color: '#EBEBEB',width: 2 })
        })
      });

      iconFeature.setStyle(iconStyle);

      var vectorSource=new ol.source.Vector({
        features: [iconFeature]
      });

      var vectorLayer=new ol.layer.Vector({
        source: vectorSource
      });
      map.addLayer(vectorLayer);

    },
    handleInfo(index,row) {
      this.lon_x=parseFloat(row.longitude);
      this.lan_y=parseFloat(row.latitude);
      this.mapVisible=true;
      setTimeout(() => {
        this.initMap();
        map.getView().setCenter(ol.proj.fromLonLat([this.lon_x,this.lan_y]));
        this.removeMarker();
        this.addMarker(row.name)
      },0);

    }


  },

  mounted() {
    this.loadMapData();
  },
  beforeDestroy() {
    // 在组件销毁前销毁地图实例
    if(map) {
      map.setTarget(null);
      map=null;
    }
  }

};
</script>

<style lang="scss" scoped>
::v-deep .el-table__body-wrapper {
  &::-webkit-scrollbar {
    width: 4px;
  }
  &::-webkit-scrollbar-thumb {
    background-color: #1296db;
    height: 6px;
    border-radius: 8px;
  }
}
</style>